package service

import (
	"echo-utils/internal/model"
	"strings"
)

type SourceItem struct {
	ini         string
	title       string
	keywords    []string
	description string
	fileHandler *EchoFile
}

func (s *SourceItem) readIni() []string {
	lines, _ := s.fileHandler.ReadLines(s.ini)
	return lines
}

func (s *SourceItem) setTitle(line string) {
	s.title = strings.TrimSpace(line)
}

func (s *SourceItem) setKeywords(line string) {
	enChar := strings.Replace(line, "，", ",", -1)
	keywords := strings.Split(enChar, ",")
	for _, v := range keywords {
		soildVal := strings.TrimSpace(v)
		if len(soildVal) > 0 {
			s.keywords = append(s.keywords, soildVal)
		}
	}
}

func (s *SourceItem) setDescription(line string) {
	s.description = strings.TrimSpace(line)
}

func (s *SourceItem) copyImage() {

}

func (s *SourceItem) Data() *model.Article {
	lines := s.readIni()
	if len(lines) < 3 {
		return nil
	}
	s.setTitle(lines[0])
	s.setKeywords(lines[1])
	s.setDescription(lines[2])

	imgs := s.fileHandler.CopyImage(s.ini)

	return &model.Article{
		Title:       s.title,
		Description: s.description,
		Keywords:    strings.Join(s.keywords, ","),
		Images:      strings.Join(imgs, ","),
		Localpath:   s.fileHandler.PathForIni(s.ini),
	}
}

func NewSourceItem(ini string, handler *EchoFile) *SourceItem {
	kw := make([]string, 0)
	return &SourceItem{
		ini:         ini,
		fileHandler: handler,
		keywords:    kw,
	}
}
